package com.jinghao.ctws.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.jinghao.core.common.exception.JingHaoCustomerException;
import com.jinghao.core.common.service.impl.JingHaoBaseServiceImpl;
import com.jinghao.core.common.util.cnd.JhCnd;
import com.jinghao.ctws.entity.CwvProcess;
import com.jinghao.ctws.entity.CwvProcess.ECWvProcess;
import com.jinghao.ctws.entity.CwvProcessConfig;
import com.jinghao.ctws.entity.CwvProduct;
import com.jinghao.ctws.entity.CwvProduct.ECWvProduct;
import com.jinghao.ctws.entity.CwvVideoPlayConfig;
import com.jinghao.ctws.service.ICwvProcessConfigService;
import com.jinghao.ctws.service.ICwvProcessService;
import com.jinghao.ctws.service.ICwvProductService;
import com.jinghao.ctws.service.ICwvPublicService;
import com.jinghao.ctws.service.ICwvVideoPlayConfigService;
import com.jinghao.ctws.service.nos.NosService;
import com.jinghao.ctws.util.EJhCTwsCode;
import com.jinghao.sys.entity.SysAccount;

@Service("cwvProductService")
public class CwvProductServiceImpl extends JingHaoBaseServiceImpl<CwvProduct> implements ICwvProductService {
	//==================定制内容开始======================
//在这里修改代码
	@Resource
	private ICwvProcessConfigService cwvProcessConfigService;
	
	@Resource
	private ICwvProcessService cwvProcessService;
	
	@Resource
	private ICwvPublicService cwvPublicService;
	
	@Resource
	private ICwvVideoPlayConfigService cwvVideoPlayConfigService;
	
	@Resource
	private NosService nosService;
	
	
	public String getCwvVideoPlayConfigInfo(){
		String address="";
		List<CwvVideoPlayConfig> list=this.cwvVideoPlayConfigService.queryModelList(new CwvVideoPlayConfig());
		if(list!=null&&list.size()>0){
			CwvVideoPlayConfig model=list.get(0);
			String serviceName=model.getServiceName();
			if(model.getServiceName()==null||model.getServiceName().trim().equals("")){
				serviceName="/";
			}
			if(!serviceName.substring(serviceName.length()-1, serviceName.length()).equals("/")){
				serviceName=serviceName+"/";
			} 
			address=model.getIp()+":"+model.getPort()+""+serviceName;
		}
		return address;
	}
	
	@Override
	public void listCwvProductByPalletId(CwvProduct model) {
		String ipAddress=this.getCwvVideoPlayConfigInfo();
		if (StringUtils.isEmpty(model.getFpalletUuid())) {
			throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"请提供托盘UUID！");
		}
		JhCnd cnd=new JhCnd();
		cnd.andEquals("fpalletUuid");
		model.setStatus(ECWvProduct.status_1.getKey());
		cnd.andEquals("p.status", "status");
		model.lnkCnd(cnd);
		cnd.append(" and pc.process_id <> 'tallying' ");
		List<Map<String,Object>> list=this.queryMapListById(model, "queryCwvProductByPalletId");
		Map<String,Object> dataMap=null;
		Date fromDate=null,toDate=null;
		String mediaInfo="";
		int i=1;
		for(Map<String,Object> map:list){
			map.put("nub", i);
			i++;
			dataMap=new HashMap<String,Object>();
			if(map.get("checkTime")==null){
				throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"checkTime为空！");
			}
			Date checkTime=(Date)map.get("checkTime");
			if(map.get("deviceId")==null){
				throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"deviceId为空！");
			}	
			dataMap.put("deviceId", Integer.parseInt(map.get("deviceId").toString()));
			if(map.get("channelId")==null){
				throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"channelId为空！");
			}	
			dataMap.put("channelId",Integer.parseInt(map.get("channelId").toString()));
			//未生成视频 
			if(map.get("urlStatus")!=null&&Integer.parseInt(map.get("urlStatus").toString())==ECWvProduct.urlStatus_0.getKey()){
				fromDate=new Date(); 
				fromDate.setTime(checkTime.getTime()-2*60*1000);
				dataMap.put("from",fromDate.getTime());
				toDate=new Date();
				toDate.setTime(checkTime.getTime()+2*60*1000);
				dataMap.put("to",toDate.getTime());
				mediaInfo=this.getMediaInfo(dataMap);
			}
			if(map.get("urlLink")!=null){
				//map.put("urlLink",(map.get("newFileName")!=null?ipAddress+map.get("newFileName").toString():""));
				map.put("urlLink", getNosOrHttpUrl((String)map.get("newFileName")));
			}
			map.put("media-info", mediaInfo);
		}
		model.setMapList(list);
	}
	
	@Override
	public void listCwvProductBySID(CwvProduct model) {
		if (StringUtils.isEmpty(model.getSpd())) {
			model.setMapList(null);
			return;
		}
		if (model.getAccessToken()==null||model.getAccessToken().trim().equals("")){
			throw new JingHaoCustomerException("accessToken值不能为空！");
		}
		SysAccount account=this.cwvPublicService.checkUserIsLoginInfo(model.getAccessToken());
		
		//Map<String,Object> map=account.getMapList().get(0);
		List<Map<String,Object>> orgList=account.getMapList();
		
		if (orgList==null||orgList.isEmpty()) {
			throw new JingHaoCustomerException("登录信息有误！");
		}
		String fjhorgUuid="";
		for(Map<String,Object> tempMap:orgList){
			if(fjhorgUuid.equals("")){
				fjhorgUuid="'"+tempMap.get("jhamoJhorgUuid").toString()+"'";
			}else{
				fjhorgUuid=fjhorgUuid+",'"+tempMap.get("jhamoJhorgUuid").toString()+"'";
			}
		}
		/*Map<String,Object> userMap=(Map<String,Object>)map.get("user");
		if (userMap==null||userMap.get("jhactCrorgUuid")==null) {
			throw new JingHaoCustomerException("登录信息有误！");
		}
		String fjhorgUuid=userMap.get("jhactCrorgUuid").toString().trim();*/
		model.getStrMap().put("fjhorgUuid", fjhorgUuid);
		
		String ipAddress=this.getCwvVideoPlayConfigInfo();
		
		//第一步：查询定单相关所有托盘信息
		JhCnd cnd=new JhCnd();
		//cnd.andEquals("spd");
		//cnd.orderBy("productUnid", ORDER.ASC);
		cnd.append(" and (spd='"+model.getSpd()+"' or order_id = '"+model.getSpd()+"' or fpallet_id = '"+model.getSpd()+"')");
		cnd.append(" and  p.fpallet_Uuid in (select pallet_Uuid from CWV_PALLET cwv where cwv.fjhorg_Uuid in ("+fjhorgUuid+"))");
		model.lnkCnd(cnd);
		model.setPage(null);
		List<Map<String,Object>> list=this.queryMapListById(model, "queryCwvProductBySPD2");
		
		CwvProduct newModel=new CwvProduct();
		newModel.setSpd(model.getSpd());
		//第二步：查询定单所有相关产品信息
		cnd.reset();
		cnd.append(" and (spd='"+newModel.getSpd()+"' or order_id = '"+newModel.getSpd()+"' or fpallet_id = '"+model.getSpd()+"')");
		cnd.append(" and  p.fpallet_Uuid in (select pallet_Uuid from CWV_PALLET cwv where cwv.fjhorg_Uuid in ("+fjhorgUuid+"))");
		newModel.lnkCnd(cnd);
		newModel.setPage(null);
		List<Map<String,Object>> productlist=this.queryMapListById(newModel, "queryCwvProductIdAndTime");
		
		//第三步:拼接数据
		String fflowUuid=null;
		CwvProcessConfig wvProModel=new CwvProcessConfig();
		CwvProcess wvProcess = new CwvProcess();
		List<Map<String,Object>> listConfig=null;
		List<Map<String,Object>> listProcess=null;
		String processId=null;
		List<List<Map<String,Object>>> aList=null;
		List<Map<String,Object>> bList=null;
		List<Map<String,Object>> bbList=null;
		Map<String,Object> dataMap=null;
		Map<String,Object> totalDataMap=null;
		String mediaInfo="";
		Date fromDate,toDate,tempDate;
		List<Map<String,Object>> proList=null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<String> strList=new ArrayList<String>();
		strList.add("temporaryTransfer");
		strList.add("tallyTransfer");
		strList.add("tallying");
		int _state=1;
		Set<String> dateSet=new HashSet<String>();
		for(Map<String,Object> tempMap:list){
			if(tempMap.get("urlStatus")==null||StringUtils.isEmpty(tempMap.get("urlStatus").toString())){
				throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"托盘记录中不存在urlStatus数据！");
			}
			_state=Integer.parseInt(tempMap.get("urlStatus").toString());
			if(tempMap.get("urlLink")!=null){
				//tempMap.put("urlLink",(null!=tempMap.get("newFileName")?ipAddress+tempMap.get("newFileName").toString():""));
				tempMap.put("urlLink", getNosOrHttpUrl((String)tempMap.get("newFileName")));
			}
			proList=new ArrayList<Map<String,Object>>();
			dateSet.clear();
			for(Map<String,Object> teMap:productlist){
				if(teMap.get("palletUuid").toString().equals(tempMap.get("fpalletUuid").toString())){
					if(!dateSet.contains(teMap.get("productId").toString())){
						try {
							if(teMap.get("createTime").toString().trim().indexOf(".")>0){
								tempDate=(Date)teMap.get("createTime");
							}else{
								tempDate=formatter.parse(teMap.get("createTime").toString().trim());
							}
						} catch (ParseException e) {
							throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"createTime时间转化异常！");
						}
						//tempDate=(Date)teMap.get("createTime");
						teMap.put("createTime", formatter.format(tempDate));
						proList.add(teMap);
						dateSet.add(teMap.get("productId").toString());
					}
				}
			}
		    if(proList.size()>0){
		    	tempMap.put("products", proList);
		    }else{
		    	tempMap.put("products", null);
		    }
			//A：根据流程ID，查看流程相关环节编码
			if(tempMap.get("fflowUuid")==null||StringUtils.isEmpty(tempMap.get("fflowUuid").toString())){
				throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"托盘记录中不存在fflowUuid数据！");
			}
			fflowUuid=tempMap.get("fflowUuid").toString();
			cnd.reset();
			cnd.andEquals("fflowUuid");
			wvProModel.setFflowUuid(fflowUuid);
			wvProModel.lnkCnd(cnd);
			wvProModel.setPage(null);
			listConfig=this.cwvProcessConfigService.queryMapListById(wvProModel, "queryMapListCwvProcessconfigByProcessId");
			//B：查询流程对应的所有环节数据 fpalletId
			cnd.reset();
			cnd.andEquals("fpalletUuid");
			wvProcess.setFpalletUuid(tempMap.get("fpalletUuid").toString());
			wvProcess.lnkCnd(cnd);
			wvProcess.setPage(null);
			listProcess=this.cwvProcessService.queryMapListById(wvProcess,"queryCwvProcessAndCamera");
			
			aList=new ArrayList<List<Map<String,Object>>>();
			//C:全成数据
			for(Map<String,Object> confMap:listConfig){
				processId=confMap.get("processId").toString();
				bbList=new ArrayList<Map<String,Object>>();
				if(_state==0&&strList.contains(processId)){
					bList=new ArrayList<Map<String,Object>>();
				}
				for(Map<String,Object> proMap:listProcess){
					if(proMap.get("fprocessId")!=null&&proMap.get("fprocessId").toString().equals(processId)){
						tempMap.put(processId+"_fprocessId", processId);
						tempMap.put(processId+"_processUuid", proMap.get("processUuid").toString());
						tempMap.put(processId+"_urlStatus",proMap.get("urlStatus").toString());
						//未生成视频的，需构建 media-info
						mediaInfo="";
						if(proMap.get("urlStatus")!=null&&Integer.parseInt(proMap.get("urlStatus").toString())==ECWvProcess.urlStatus_0.getKey()){
							dataMap=new HashMap<String,Object>();
							dataMap.put("deviceId", Integer.parseInt(proMap.get("deviceId").toString()));
							dataMap.put("channelId", Integer.parseInt(proMap.get("channelId").toString()));
							if(proMap.get("startTime")==null||proMap.get("endTime")==null){
								throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"数据错误，流程环节信息中，startTime或endTime为空");
							}
							fromDate=(Date)proMap.get("startTime");
							toDate=(Date)proMap.get("endTime");
							dataMap.put("from", fromDate.getTime());
							dataMap.put("to", toDate.getTime());
							//mediaInfo=this.getMediaInfo(dataMap);
							bbList.add(dataMap);
	
							tempMap.put(processId+"_urlLink","");
						}else{
							if(proMap.get("urlLink")==null||StringUtils.isEmpty(proMap.get("urlLink").toString())){
								throw new JingHaoCustomerException(EJhCTwsCode.TWS6001.getCode(),"数据错误，已生成视频数据，urlLink不能为空");
							}
							//tempMap.put(processId+"_urlLink",(proMap.get("newFileName")!=null?ipAddress+proMap.get("newFileName").toString():""));
							tempMap.put(processId+"_urlLink", getNosOrHttpUrl(proMap.get("newFileName")!=null?(String)proMap.get("newFileName").toString():""));
						}
						if(_state==0&&strList.contains(processId)){
							fromDate=(Date)proMap.get("startTime");
							toDate=(Date)proMap.get("endTime");
							totalDataMap=new HashMap<String,Object>();
							totalDataMap.put("deviceId", Integer.parseInt(proMap.get("deviceId").toString()));
							totalDataMap.put("channelId", Integer.parseInt(proMap.get("channelId").toString()));
							totalDataMap.put("from", fromDate.getTime());
							totalDataMap.put("to", toDate.getTime());
							bList.add(totalDataMap);
						}
					}
				}
				tempMap.put(processId+"_mediaInfo",this.getMediaInfoByList(bbList));
				if(_state==0&&strList.contains(processId)){
					if(bList.size()>0){
						aList.add(bList);
					}
				}
			}
			if(_state==0){
				tempMap.put("media-info", JSON.toJSONString(aList));
			}else{
				tempMap.put("media-info", "");
			}
		}
		model.setMapList(list);
	}
	
	public String getMediaInfo(Map<String,Object> dataMap){
		List<List<Map<String,Object>>> aList=null;
		List<Map<String,Object>> bList=null;
		aList=new ArrayList<List<Map<String,Object>>>();
		bList=new ArrayList<Map<String,Object>>();
		bList.add(dataMap);
		aList.add(bList);
		return JSON.toJSONString(aList);
		
	}
	
	public String getMediaInfoByList(List<Map<String,Object>> bList){
		List<List<Map<String,Object>>> aList=null;
		aList=new ArrayList<List<Map<String,Object>>>();
		aList.add(bList);
		return JSON.toJSONString(aList);
	}

	private String getNosOrHttpUrl(String objectName) {
		if (StringUtils.isBlank(objectName)) {
			return null;
		}
		String ipAddress=this.getCwvVideoPlayConfigInfo();
		String httpUrl = ipAddress + objectName;
		String nosUrl = nosService.getObjectUrl(objectName);
		if (StringUtils.isNotBlank(nosUrl)) {
			return nosUrl;
		}
		return httpUrl;
	}
	//==================定制内容结束======================
}
